const api = require('../../utils/api.js');
const app = getApp();
const { gatherAction = '', reportAction = '' } = require('../../utils/utils');
Page({
  data: {
    total_price: 0.0,
    total_count: 0,
    cart_check_all: false,
    cart_list: [],
    theme: app.themeData,
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-22.png',
      text: '购物车空空如也',
    },
    unit: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    imgUrl: app.imgUrl,
    isBrand: app.ws_micro_shop_globalData.isBrand
  },

  onLoad(options) {
    let that = this;
    let opts = options || {};
    app.pageOnLoad(this);
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    let isMulti =
      app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isMulti; // 是否为多店
    this.setData({
      opts,
      isMulti: isMulti || false,
      useTabbar: that.data.useTabbar && app.getTabBarStatus(),
    });
    app.v8_card_seller_actions_log = [];
  },

  onShow() {
    wx.showTabBar();
    this.setData({
      cart_check_all: false,
      show_cart_edit: false,
      total_count: 0,
    });
    this.getCartList();

    let fromHome =
      (app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.fromHome) ||
      false;
    this.setData({ fromHome }, () => {
      // app.ws_micro_shop_globalData.fromHome = false;
    });
    fromHome &&
      wx.hideTabBar() &&
      this.setData({
      useTabbar: this.data.useTabbar && app.getTabBarStatus(),
      });
  },

  getCartList() {
    let type = app.siteInfo.tabbar_type;
    let _this = this;
    _this.setData({
      show_no_data_tip: false,
    });
    app.ws_micro_shoprequest({
      url: api.cart.listNew,
      success: function(res) {
        if (res.code === 0) {
          let { list, shop_list: shopList,is_cart } = res.data;
          let showList = [];
          _this.data.isMulti &&
            shopList.forEach(item => {
              // 兼容单多店
              showList.push(list.filter(i => i.shop_id === item.shop_id));
            });
          _this.setData({
            cart_list: list,
            shopList,
            showList,
            total_price: 0.0,
            cart_check_all: false,
            show_cart_edit: false,
            is_cart:is_cart
          });
          let tabBarIndex = _this.getCurrentTabBerIndex();
          if (Number(type) === 1 && list.length > 0) {
            _this.setNumber(list);
          } else {
            !Number.isNaN(tabBarIndex) &&
              wx.removeTabBarBadge({
                index: tabBarIndex,
              });
          }
        }
        _this.setData({
          show_no_data_tip: _this.data.cart_list.length === 0,
        });
      },
    });
  },

  setNumber(list) {
    let index = this.getCurrentTabBerIndex();
    if (index) {
      wx.setTabBarBadge({
        index,
        text: String(this.calcTotalCount(list)),
      });
    }
  },

  getCurrentTabBerIndex() {
    let list = app.siteInfo.appJson[0].tabBar.list;
    let path = this.route;
    for (let i in list) {
      if (list[i].pagePath === path) {
        return Number(i);
      }
    }
  },

  calcTotalCount(list) {
    let total = 0;
    for (let i in list) {
      if (Object.prototype.hasOwnProperty.call(list, i)) {
        total += Number(list[i].num);
      }
    }
    return total;
  },

  cartLess(index) {
    let cart_list = this.data.cart_list;
    for (let i in cart_list) {
      if (Number(index.currentTarget.id) === Number(cart_list[i]['cart_id'])) {
        // 起购
        let minNum =
          Number(cart_list[i].min_num) > 1 ? Number(cart_list[i].min_num) : 1;
        if (cart_list[i]['num'] <= minNum) {
          wx.showToast({
            title: '已达到最小购买数量',
            icon: 'none',
          });
          return;
        }
        cart_list[i]['num'] = this.data.cart_list[i]['num'] - 1;
        if (cart_list[i]['num'] <= cart_list[i]['max_num']) {
          cart_list[i]['disabled'] = false;
        }
        cart_list[i]['price'] =
          this.data.cart_list[i]['unitPrice'] * cart_list[i]['num'];
        this.setData({
          cart_list,
        });
        this.setNumber(cart_list);
        this.updateTotalPrice({ cartID: index.currentTarget.id });
      }
    }
  },

  cartAdd(index) {
    let cart_list = this.data.cart_list;
    let able_count;
    for (let i in cart_list) {
      if (Number(index.currentTarget.id) === Number(cart_list[i]['cart_id'])) {
        if (cart_list[i]['limit_count'] > 0) {
          able_count =
            cart_list[i]['limit_count'] -
            cart_list[i]['user_order_count'].order;
          if (cart_list[i]['num'] < able_count) {
            cart_list[i]['num'] = this.data.cart_list[i]['num'] + 1;
          } else {
            wx.showToast({
              title: '已达到最大购买数量',
              icon: 'none',
            });
            return;
          }
        } else {
          cart_list[i]['num'] = this.data.cart_list[i]['num'] + 1;
        }
        cart_list[i]['price'] =
          this.data.cart_list[i]['unitPrice'] * cart_list[i]['num'];
        this.setData({
          cart_list,
        });
        this.setNumber(cart_list);
        this.updateTotalPrice({ cartID: index.currentTarget.id });
      }
    }
  },

  cartCheck(e) {
    let { cartId } = e.currentTarget.dataset;
    let cart_list = this.data.cart_list;
    let num = 0;
    let index = cart_list.findIndex(item => item.cart_id === Number(cartId));
    cart_list[index].checked = !cart_list[index].checked;
    for (let i in cart_list) {
      if (Object.prototype.hasOwnProperty.call(cart_list, i)) {
        cart_list[i].checked === true && num++;
      }
    }
    this.setData({
      cart_list,
      cart_check_all: num === cart_list.length,
    });
    this.updateTotalPrice({ cartID: cartId });
  },

  cartCheckAll() {
    let { cart_list, cart_check_all, show_cart_edit } = this.data;
    let checked = !cart_check_all;
    for (let i in cart_list) {
      if (!cart_list[i].disabled || show_cart_edit) {
        cart_list[i].checked = checked;
      }
    }
    this.setData({
      cart_check_all: checked,
      cart_list,
    });
    this.updateTotalPrice();
  },

  updateTotalPrice({ cartID = '' } = {}) {
    let total_price = 0.0;
    let total_count = 0;
    let { cart_list, showList, isMulti } = this.data;
    for (let i = 0; i < cart_list.length; i++) {
      if (cart_list[i].checked) {
        total_price += cart_list[i].price;
        total_count += cart_list[i].num;
      }
    }
    isMulti &&
      cartID &&
      showList.forEach(item => {
        item.forEach(_item => {
          if (_item.cart_id === Number(cartID)) {
            _item.num = cart_list.find(i => i.cart_id === Number(cartID)).num;
            _item.checked = cart_list.find(
              i => i.cart_id === Number(cartID)
            ).checked;
          }
        });
      });

    this.setData({
      total_price: total_price.toFixed(2),
      total_count,
      showList,
    });
  },

  cartSubmit() {
    let that = this;
    let cart = JSON.stringify(that.data.cart_list);
    if (cart === '[]') {
      return;
    } else {
      if (Number(that.data.total_price) === 0 && Number(that.data.total_count) === 0) {
        wx.showToast({
          title: '请选择要购买的商品',
          icon: 'none',
        });
      }
    }
    // 骑手不支持跨店支付做的处理 jane
          let cart_list = that.data.cart_list;
    let rider_list = [];
    let cart_id_list = [];
    let goods_id_list = [];
    for (let i in cart_list) {
      if (cart_list[i].checked) {
        rider_list.push(cart_list[i]);
        cart_id_list.push(cart_list[i].cart_id);
        goods_id_list.push(cart_list[i].goods_id);
      }
    }
    app.ws_micro_shoprequest({
      url: api.cart.cart_account,
      method: 'POST',
      data: {
        list: JSON.stringify(rider_list),
      },
      success: function(res) {
        if (res.code === 0) {
          if (cart_id_list.length === 0) {
            return true;
          }
          app.util.navigateTo(
          '/ws_micro_shop/pages/order-submit/order-submit',{
            cart_id_list: JSON.stringify(cart_id_list),
            goods_id_list: JSON.stringify(goods_id_list)
          }, false);
        }
        if (res.code === 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });

    app.ws_micro_shoprequest({
      url: api.cart.cart_edit,
      method: 'POST',
      data: {
        list: cart,
      },
      success: function(res) {
    
      },
    });
  },

  cartEdit() {
    let cart_list = this.data.cart_list;
    for (let i in cart_list) {
      if (Object.prototype.hasOwnProperty.call(cart_list, i)) {
        cart_list[i].checked = false;
      }
    }
    this.setData({
      cart_list,
      show_cart_edit: true,
      cart_check_all: false,
    });
    this.updateTotalPrice();
  },

  cartDone() {
    let cart_list = this.data.cart_list;
    for (let i in cart_list) {
      if (Object.prototype.hasOwnProperty.call(cart_list, i)) {
        cart_list[i].checked = false;
      }
    }
    this.setData({
      cart_list,
      show_cart_edit: false,
      cart_check_all: false,
    });
    this.updateTotalPrice();
  },

  cartDelete() {
    let that = this;
    let cart_list = that.data.cart_list;
    let cart_id_list = [];
    for (let i in cart_list) {
      if (cart_list[i].checked) {
        cart_id_list.push(cart_list[i].cart_id);
      }
    }
    if (cart_id_list.length === 0) {
      wx.showModal({
        title: '提示',
        content: '请选择要删除的商品',
        showCancel: false,
      });
      return true;
    }
    wx.showModal({
      title: '提示',
      content: '确认删除' + cart_id_list.length + '项内容？',
      success: function(res) {
        if (res.cancel) {
          return true;
        }
        wx.showLoading({
          title: '正在删除',
          mask: true,
        });
        app.ws_micro_shoprequest({
          url: api.cart.delete,
          data: {
            cart_id_list: JSON.stringify(cart_id_list),
          },
          success: function(res) {
            wx.hideLoading();
            that.setData({
              total_count: 0,
            });
            wx.showToast({
              title: res.msg || '',
              icon: 'none',
            });
            if (res.code === 0) {
              that.getCartList();
            }
          },
        });
      },
    });
  },

  removeGoods(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let inx = e.currentTarget.dataset.inx;
    let { cart_list, isMulti, showList } = that.data;
    let cart_id_list = [];
    let cart_id = isMulti ? showList[index][inx].cart_id : cart_list[index].cart_id;
    cart_id_list.push(cart_id);
    wx.showModal({
      title: '提示',
      content: '确认删除该商品吗？',
      success: function(res) {
        if (res.cancel) {
          return true;
        }
        wx.showLoading({
          title: '正在删除',
          mask: true,
        });
        app.ws_micro_shoprequest({
          url: api.cart.delete,
          data: {
            cart_id_list: JSON.stringify(cart_id_list),
          },
          success: function(res) {
            wx.hideLoading();
            that.setData({
              total_count: 0,
            });
            wx.showToast({
              title: res.msg,
              icon: 'none'
            });
            if (res.code === 0) {
              that.getCartList();
            }
          },
        });
      },
    });
    gatherAction &&
      gatherAction('removeGoods', 'success', {
        goodsID: cart_id,
      });
  },

  onHide() {
    let cart = JSON.stringify(this.data.cart_list);
    if (cart === '[]') {
      return;
    }
    app.ws_micro_shoprequest({
      url: api.cart.cart_edit,
      method: 'POST',
      data: {
        list: cart,
      },
    });
    reportAction && reportAction();
  },

  onUnload() {
    let cart = JSON.stringify(this.data.cart_list);
    if (cart === '[]') {
      return;
    }
    app.ws_micro_shoprequest({
      url: api.cart.cart_edit,
      method: 'POST',
      data: {
        list: cart,
      },
    });
    reportAction && reportAction();
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  scanBarCode() {
    let that = this;
    wx.scanCode({
      success(res) {
        app.ws_micro_shoprequest({
          url: api.cart.scanadd,
          method: 'POST',
          data: {
            code: res.result,
          },
          success: function(resp) {
            if (resp.code === 0) {
              wx.showModal({
                title: '提示',
                content: '添加成功',
                showCancel: false,
                confirmText: '确认',
                success: function(res) {
                  if (res.confirm) {
                    that.getCartList();
                  }
                },
              });
            } else {
              wx.showToast({
                title: '添加失败',
                icon: 'none',
              });
            }
          },
        });
      },
    });
  },

  homeNavigation(e) {
    app.ws_micro_shop_globalData.fromHome = true;
    let url =
      e.currentTarget.dataset.type === 'center'
        ? 'ws_micro_shop/pages/user/user'
        : 'ws_micro_shop/pages/home/index';
    app.util.navigateTo(url, {}, true);
  },
});
